package com.kgc.dubbo.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.kgc.dubbo.component.AlipayConfig;
import com.kgc.dubbo.entity.QgGoodsTempStock;
import com.kgc.dubbo.entity.QgOrder;
import com.kgc.dubbo.entity.QgTrade;
import com.kgc.dubbo.service.LocalPayService;
import com.kgc.dubbo.service.QgGoodsTempStockService;
import com.kgc.dubbo.service.QgOrderService;
import com.kgc.dubbo.service.QgTradeService;
import com.kgc.dubbo.utils.Constants;
import com.kgc.dubbo.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.*;

@Service
public class LocalPayServiceImpl implements LocalPayService {

    @Autowired
    private AlipayConfig alipayConfig;
    @Reference
    private QgTradeService qgTradeService;
    @Reference
    private QgGoodsTempStockService qgGoodsTempStockService;
    @Reference
    private QgOrderService qgOrderService;

    @Override
    public void aliPay(String orderId, HttpServletResponse response) throws Exception {
        //根据订单编号查询订单
        QgOrder qgOrder = qgOrderService.getQgOrderById(orderId);
        String WIDout_trade_no = qgOrder.getOrderNo();
        String WIDtotal_amount = String.valueOf(qgOrder.getAmount());
        String WIDsubject = qgOrder.getGoodsId();
        String product_code = "FAST_INSTANT_TRADE_PAY";
        //获得初始化的AlipayClient
        AlipayClient alipayClient =
                new DefaultAlipayClient(alipayConfig.getGatewayUrl(),
                        alipayConfig.getAppId(),
                        alipayConfig.getMerchantPrivateKey(),
                        "json",
                        alipayConfig.getCharset(),
                        alipayConfig.getAlipayPublicKey(),
                        alipayConfig.getSignType());
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
        // 封装请求支付信息
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(WIDout_trade_no);
        model.setTotalAmount(WIDtotal_amount);
        model.setSubject(WIDsubject);
        //model.setTimeExpire(timeout_express);
        model.setProductCode(product_code);//必须设置这个属性，产品编码
        alipayRequest.setBizModel(model);
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //输出
        out.println(result);
        out.flush();
        out.close();

    }

    @Override
    public String aliPayReturn(HttpServletRequest request) throws Exception {
        //根据请求获取支付宝回调参数
        Map<String, String> params = this.getAliPayCallBackParams(request);
        //验证签名，如果返回true表示验证签名成功
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getCharset(),
                alipayConfig.getSignType()); //调用SDK验证签名
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        if(!signVerified) {//验签失败
            String faliureUrl = alipayConfig.getPayFailUrl();
            return String.format(faliureUrl,out_trade_no);
        }
        this.qdtxModifyPayResult(out_trade_no,trade_no, Constants.PayType.ALIPAY);
        String successUrl = alipayConfig.getPaySuccessUrl();
        return String.format(successUrl,out_trade_no);

    }

    @Override
    public void aliPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
//获取支付宝POST过来反馈信息
        Map<String, String> params = this.getAliPayCallBackParams(request);
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getCharset(),
                alipayConfig.getSignType()); //调用SDK验证签名
        /* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        PrintWriter out = response.getWriter();
        if(!signVerified) {//验证失败
            out.println("fail");
            out.flush();
            out.close();
            return ;
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
        //如果代码能走到这里说明验证签名成功
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //代码走到这里说明支付成功,调用业务逻辑层执行修改订单的操作和添加支付交易记录
        this.qdtxModifyPayResult(out_trade_no,trade_no, Constants.PayType.ALIPAY);
        //调用接口刷新库存：
        //String s = UrlUtils.loadURL("http:localhost:8083/biz//api/hotelorder/scanTradeEnd");
        out.println("success");
        out.flush();
        out.close();
    }

    private Map<String, String> getAliPayCallBackParams(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

    private QgOrder qdtxModifyPayResult(String orderNo, String tradeNo, Integer payType) throws Exception {
        QgOrder qgOrder = null;
        //判断该条订单是否已被处理（根据订单编号和支付状态去订单表中查询是否存在该条记录）
        Map<String,Object> params = new HashMap<>();
        params.put("orderNo",orderNo);
        params.put("tradeNo",tradeNo);
        Integer count = qgTradeService.getQgTradeCountByMap(params);
        if(count>0){//表示该条订单已经被处理
            return null;
        }
        //根据订单编号查询订单信息
        Map<String,Object> orderParams = new HashMap<>();
        orderParams.put("orderNo",orderNo);
        List<QgOrder> qgOrderList = qgOrderService.getQgOrderListByMap(orderParams);
        if(qgOrderList!=null && qgOrderList.size()==1){
            qgOrder = qgOrderList.get(0);
            //修改临时库存表中的相应支付的支付状态
            QgGoodsTempStock tempStock = new QgGoodsTempStock();
            tempStock.setId(qgOrder.getStockId());
            tempStock.setStatus(Constants.PayStatus.PAY_SUCCESS);
            qgGoodsTempStockService.qdtxModifyQgGoodsTempStock(tempStock);
            //修改相应订单的支付状态
            qgOrder.setStatus(Constants.PayStatus.PAY_SUCCESS);
            qgOrder.setAliTradeNo(tradeNo);
            qgOrderService.qdtxModifyQgOrder(qgOrder);
            //向交易表中插入一条数据
            QgTrade qgTrade = new QgTrade();
            qgTrade.setId(IdWorker.getId());
            qgTrade.setAmount(qgOrder.getAmount());
            qgTrade.setCreatedTime(new Date());
            qgTrade.setOrderNo(orderNo);
            qgTrade.setPayMethod(payType);
            qgTrade.setTradeNo(tradeNo);
            qgTrade.setUpdatedTime(new Date());
            qgTradeService.qdtxAddQgTrade(qgTrade);
            return qgOrder;
        }
        return null;
    }

}
